<template>
  <div class="container">
    <div class="u-title f-mtp10">
      <h2>{{n_title}}</h2>
    </div>

    <div class="u-content mn flex flex-column flex-center">
      <div class="item">
        <label class='tip' for>公告标题：</label>
        <div class="item-right">
          <el-input v-model="title" placeholder="公告标题"></el-input>
        </div>
      </div>
      <div class="item">
        <label for>公告封面</label>
        <div class="item-right">
          <div class="u-upload">
            <input
              type="file"
              @change="upCoverImg"
              name="file"
              id="file"
              accept="image/png, image/jpeg, image/gif, image/jpg"
              class="u-upload-file"
            >
            <label for="file" class="btn btn-success">
              <img v-if="picUrl" :src="picUrl" alt>
              <i class="el-icon-plus" v-else></i>
            </label>
          </div>
        </div>
      </div>
      <div class="item">
        <label class='tip' for>公告描述：</label>
        <div class="item-right">
          <el-input type="textarea" :rows="4" v-model="description" placeholder="公告描述"></el-input>
        </div>
      </div>

      <div class="item">
        <label class='tip' for>内容详情：</label>
        <div class="item-right">
          <quill-editor
            v-model="content"
            ref="myQuillEditor"
            :options="editorOption"
            @change="onEditorChange"
          ></quill-editor>
          <input v-show='false' type="file" @change="upImg" id='upImg' ref="upImg" accept="image/png, image/jpeg, image/gif, image/jpg" />
        </div>
      </div>
      <div class="btn-box f-ptp20">
        <el-button class="f-w300 s-bg-green s-cfff" @click="submit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import config from '../../config';
export default {
  name: "AddNotice",
  data() {
    return {
      n_title: "发布公告",
      content: "",
      picUrl: '',
      editorOption: {
        theme: "snow",
        placeholder: "请在此输入内容详情...",
        modules: {
          toolbar: {
            container: config.toolbarOptions,
            handlers: {
              'image': function(value) {
                if(value) {
                  document.querySelector('#upImg').click()
                } else {
                  this.quill.format('image', false);
                }
                
              }
            }
          }
        }
      },
      id: null,
      description: "",
      title: ""
    };
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    }
  },
  mounted() {
    console.log("this is current quill instance object", this.editor);
  },
  created: function() {
    if (this.$route.params.id) {
      this.id = this.$route.params.id;
      this.n_title = "编辑公告";
      this.getNoticeDetailById(this.id);
    }
  },
  methods: {
    // 上传封面图片
    upCoverImg(e) {
      this.upfile(e, 'cover')
    },
    // 富文本上传图片
    upImg(e) {
      this.upfile(e, 'editor')
    },
    // 上传
    upfile(e, type) {
      const files = e.target.files;
      const form = new FormData();
      form.append("file", files[0]);
      form.append("dir", "notice");
      form.append("type", "1");
      this.$store.dispatch("UPLOAD_FILE", form).then(res => {
        if (res.data.retCode == 0) {
          this.$message.success("上传成功！");
          if(type == 'cover') {
            this.picUrl = res.data.data;
          }
          if(type == 'editor') {
            // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.data.data)
            // 调整光标到最后
            quill.setSelection(length + 1)
          }
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },
    
    // 获取公告详情
    getNoticeDetailById(noticeId) {
      this.$store
        .dispatch("GET_NOTICE_DETAIL", {
          id: noticeId
        })
        .then(res => {
          if (res.data.retCode == 0) {
            const notice = res.data.data;
            this.title = notice.title;
            this.content = notice.content;
            this.picUrl = notice.picUrl;
            this.description = notice.description;
          } else {
            res.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        });
    },
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill, html, text);
      this.content = html;
    },
    // 提交按钮点击事件
    submit() {
      if (this._utils.isEmpty(this.title)) {
        this.$message.warning("请输入标题！");
        return;
      }
      if (this._utils.isEmpty(this.description)) {
        this.$message.warning("请输入描述！");
        return;
      }
      if (this._utils.isEmpty(this.content)) {
        this.$message.warning("请输入内容详情！");
        return;
      }
      this.handleNotice();
    },

    // 添加、编辑公告
    handleNotice() {
      this.$store
        .dispatch("HANDLE_NOTICE", {
          id: this.id,
          title: this.title,
          description: this.description,
          picUrl: this.picUrl,
          content: this.content
        })
        .then(res => {
          if (res.data.retCode == 0) {
            this.$message.success("提交成功！");
            this.$router.push("/home/notice");
          } else {
            res.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
  line-height: 24px;
}

.container {
  width: 900px;
  /* margin: 0 auto; */
}
.mn {
  padding: 30px 0 50px 0;
}
.item {
  display: flex;
  margin-bottom: 10px;
}
.item > label {
  display: inline-block;
  width: 90px;
  line-height: 40px;
  text-align: right;
  margin-right: 10px;
}
.item > .tip::before {
  content: "*";
  line-height: 40px;
  color: red;
  margin-right: 5px;
}
.item-right {
  width: 700px;
}
.btn-box {
  padding-left: 90px;
}
</style>
